package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserCheckin(param map[string]interface{}) (*models_main.UserCheckin, error) {
	fName := "GetUserCheckin"
	o := &models_main.UserCheckin{}
	table := mysql.GetRTable(&models_main.UserCheckin{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Order("id asc").
		Limit(1).
		Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertUserCheckin(checkin *models_main.UserCheckin) error {
	fName := "InsertUserCheckin"
	err := global.GetX().Create(checkin).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserCheckin(columns []string, checkin *models_main.UserCheckin) error {
	fName := "UpdateUserCheckin"
	err := global.GetX().Where("uid = ?", checkin.Uid).Select(columns).Updates(checkin).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserCheckinByTransactions(session *gorm.DB, columns []string, checkin *models_main.UserCheckin) error {
	fName := "UpdateUserCheckinByTransactions"
	err := session.Where("uid = ?", checkin.Uid).Select(columns).Updates(checkin).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func GetUserCheckInByUid(uid int) (*models_main.UserCheckin, error) {
	fName := "GetUserCheckInByUid"
	var cki models_main.UserCheckin
	table := mysql.GetRTable(&models_main.UserCheckin{})
	err := table.Where("uid=?", uid).First(&cki).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		return nil, err
	}
	return &cki, nil
}

func InsertUserCheckinByTx(session *gorm.DB, checkin *models_main.UserCheckin) error {
	fName := "InsertUserCheckin"
	err := session.Create(checkin).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
